<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>我的购物车 - 图书购物车系统</title>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', Arial, sans-serif;
      background-color: #f5f7fa;
      color: #333;
    }
    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      background: linear-gradient(135deg, #1e5799 0%,#207cca 51%,#2989d8 100%);
      color: white;
      padding: 20px 0;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      position: sticky;
      top: 0;
      z-index: 1000;
    }
    .header-content {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .logo {
      font-size: 24px;
      font-weight: bold;
      display: flex;
      align-items: center;
    }
    .logo i {
      margin-right: 10px;
      font-size: 28px;
    }
    .nav {
      display: flex;
    }
    .nav-item {
      margin-left: 30px;
      cursor: pointer;
      font-size: 16px;
      transition: color 0.3s;
      padding: 5px 10px;
      border-radius: 4px;
      position: relative;
    }
    .nav-item:hover {
      background-color: rgba(255, 255, 255, 0.1);
    }
    .cart-count {
      position: absolute;
      top: -8px;
      right: -8px;
      background-color: #e74c3c;
      color: white;
      border-radius: 50%;
      width: 20px;
      height: 20px;
      font-size: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .page-title {
      font-size: 24px;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;
      color: #1e5799;
    }
    .back-button {
      margin-top: 30px;
      text-align: center;
    }
    .footer {
      text-align: center;
      padding: 30px 0;
      color: #909399;
      font-size: 14px;
      margin-top: 50px;
      border-top: 1px solid #ebeef5;
    }
    .empty {
      text-align: center;
      padding: 50px 0;
      font-size: 16px;
      color: #909399;
    }
    .empty i {
      font-size: 50px;
      color: #c0c4cc;
      margin-bottom: 20px;
    }
    .cart-container {
      background: white;
      border-radius: 6px;
      padding: 30px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    .cart-item {
      display: flex;
      padding: 20px 0;
      border-bottom: 1px solid #ebeef5;
    }
    .cart-item-image {
      width: 100px;
      height: 150px;
      background-color: #f5f7fa;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
      border-radius: 4px;
      overflow: hidden;
    }
    .cart-item-image img {
      max-width: 100%;
      max-height: 100%;
    }
    .cart-item-info {
      flex-grow: 1;
    }
    .cart-item-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #303133;
    }
    .cart-item-price {
      color: #e74c3c;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
    }
    .cart-item-meta {
      color: #909399;
      font-size: 14px;
      margin-bottom: 10px;
    }
    .cart-item-actions {
      display: flex;
      align-items: center;
      margin-top: 10px;
    }
    .cart-summary {
      margin-top: 30px;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 6px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .cart-total {
      font-size: 18px;
      font-weight: bold;
    }
    .total-price {
      color: #e74c3c;
      font-size: 24px;
    }
    .cart-buttons {
      display: flex;
      gap: 15px;
    }
    @media (max-width: 768px) {
      .cart-item {
        flex-direction: column;
      }
      .cart-item-image {
        width: 100%;
        height: 200px;
        margin-right: 0;
        margin-bottom: 15px;
      }
      .cart-summary {
        flex-direction: column;
        gap: 20px;
        align-items: flex-start;
      }
    }
  </style>
</head>
<body>
<div id="app">
  <!-- 顶部导航 -->
  <div class="header">
    <div class="header-content">
      <div class="logo">
        <i class="el-icon-reading"></i>
        图书购物车系统
      </div>
      <div class="nav">
        <a href="bookList.html" class="nav-item">图书列表</a>
        <a href="myCar1.html" class="nav-item">
          购物车
          <span v-if="cartCount > 0" class="cart-count">{{ cartCount }}</span>
        </a>
      </div>
    </div>
  </div>

  <div class="container">
    <div class="back-button">
      <el-button type="primary" icon="el-icon-arrow-left" @click="goToList">返回列表</el-button>
    </div>

    <h1 class="page-title">我的购物车</h1>

    <div v-if="cartItems.length > 0" class="cart-container">
      <div v-for="item in cartItems" :key="item.carId" class="cart-item">
        <div class="cart-item-image">
          <img :src="getBookImage(item.bookImage)" alt="图书封面">
        </div>
        <div class="cart-item-info">
          <div class="cart-item-title">{{ item.bookName }}</div>
          <div class="cart-item-price">¥{{ (item.bookPrice * item.carCount).toFixed(2) }}</div>
          <div class="cart-item-meta">
            <div>单价: ¥{{ item.bookPrice.toFixed(2) }}</div>
            <div>数量: {{ item.carCount }}</div>
            <div>添加时间: {{ formatDate(item.createTime) || '未知' }}</div>
          </div>
          <div class="cart-item-actions">
            <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="small"
                    @click="removeCartItem(item.carId)">
              删除
            </el-button>
          </div>
        </div>
      </div>

      <div class="cart-summary">
        <div class="cart-total">
          总计: <span class="total-price">¥{{ totalCartPrice.toFixed(2) }}</span>
        </div>
        <div class="cart-buttons">
          <el-button type="info" @click="goToList">继续购物</el-button>
          <el-button type="success" @click="checkout">结算订单</el-button>
        </div>
      </div>
    </div>

    <div v-else class="empty">
      <i class="el-icon-shopping-cart-2"></i>
      <p>购物车空空如也</p>
      <el-button type="primary" @click="goToList" style="margin-top: 20px;">去挑选图书</el-button>
    </div>
  </div>

  <div class="footer">
    © 2023 图书购物车系统 | 前端使用ElementUI+Axios实现
  </div>
</div>

<script>
  new Vue({
    el: '#app',
    data() {
      return {
        cartItems: [],
        cartCount: 0,
        books: []
      };
    },
    computed: {
      totalCartPrice() {
        return this.cartItems.reduce((total, item) => {
          return total + (item.bookPrice * item.carCount);
        }, 0);
      }
    },
    mounted() {
      this.fetchCartItems();
      this.fetchBooks();
    },
    methods: {
      fetchCartItems() {
        const userId = "93";
        axios.get(`http://localhost:8081/car/getCarByUser/${userId}`)
                .then(response => {
                  this.cartItems = response.data;
                  this.cartCount = this.cartItems.reduce((count, item) => count + item.carCount, 0);

                  // 如果已经获取到图书数据，则更新图书信息
                  if (this.books.length > 0) {
                    this.updateBookInfo();
                  }
                })
                .catch(error => {
                  console.error('获取购物车数据失败:', error);
                  this.$message.error('获取购物车数据失败');
                });
      },

      fetchBooks() {
        axios.get('http://localhost:8081/books/queryBooks')
                .then(response => {
                  this.books = response.data;

                  // 如果已经获取到购物车数据，则更新图书信息
                  if (this.cartItems.length > 0) {
                    this.updateBookInfo();
                  }
                })
                .catch(error => {
                  console.error('获取图书列表失败:', error);
                });
      },

      updateBookInfo() {
        this.cartItems.forEach(item => {
          const book = this.books.find(b => b.bookId === item.bookId);
          if (book) {
            item.bookName = book.bookName;
            item.bookPrice = book.bookPrice;
            item.bookImage = book.bookImage;
          }
        });
      },
      // 完善后的删除方法
      removeCartItem(carId) {
        this.$confirm('确定要删除该商品吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 设置当前正在删除的商品ID
          this.removingItemId = carId;

          // 调用后端删除接口
          axios.delete(`http://localhost:8081/car/deleteCar/${carId}`)
                  .then(response => {
                    if (response.data.success) {
                      // 删除成功，从本地购物车中移除该商品
                      this.cartItems = this.cartItems.filter(item => item.carId !== carId);
                      // 更新购物车数量
                      this.cartCount = this.cartItems.reduce((count, item) => count + item.carCount, 0);
                      this.$message.success('已从购物车移除');
                    } else {
                      this.$message.error('删除失败: ' + (response.data.message || '未知错误'));
                    }
                  })
                  .catch(error => {
                    console.error('删除购物车商品失败:', error);
                    this.$message.error('删除购物车商品失败: ' + (error.response?.data?.message || '网络错误'));
                  })
                  .finally(() => {
                    // 无论成功或失败，都重置删除状态
                    this.removingItemId = null;
                  });
        }).catch(() => {
          this.$message.info('已取消操作');
        });
      },
      // removeCartItem(carId) {
      //   this.$confirm('确定要删除该商品吗?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     // 在实际项目中这里应该调用删除接口
      //     // 这里模拟删除操作
      //     this.cartItems = this.cartItems.filter(item => item.carId !== carId);
      //     this.cartCount = this.cartItems.reduce((count, item) => count + item.carCount, 0);
      //     this.$message.success('已从购物车移除');
      //   }).catch(() => {
      //     this.$message.info('已取消操作');
      //   });
      // },

      checkout() {
        this.$confirm(`确定要结算吗? 总金额: ¥${this.totalCartPrice.toFixed(2)}`, '确认结算', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          this.$message.success('结算成功，订单已生成');
          // 清空购物车
          this.cartItems = [];
          this.cartCount = 0;
        }).catch(() => {
          this.$message.info('已取消结算');
        });
      },

      goToList() {
        window.location.href = 'bookList.html';
      },

      getBookImage(imageName) {
        return imageName ? `images/books/${imageName}` : 'https://via.placeholder.com/200x280?text=No+Image';
      },

      formatDate(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      }
    }
  });
</script>
</body>
</html>